/**
 * 消息页
 */
import React, { PureComponent } from 'react';
import {
  Image,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ScrollView,
  Platform,
} from 'react-native';
import { connect } from 'react-redux';
import ImagePicker from 'react-native-image-picker';
import CodePush from 'react-native-code-push';
import actions from '../../models/actions';
import NavigationBar from '../../components/navigationBar';
import image from '../../assets/image';
import {
  LoginToken,
  safeAreaBottomHeight,
  screenWidth,
} from '../../util/AdapterUtil';
import NavigationService from '../../components/NavigationService';
import AlertView from '../../components/AlertView';

import { QNEngine } from '../../native/QNEngine';
import * as requestApi from '../../util/requestApi';
import { token } from '../../models/user/reducer';
// let Code_Push_Key = "Y0yM5lrPkEKUGjJvhaPQX6pwRUv74ksvOXqog"
const Code_Push_Key = '8OXYzPMfILrPzq0lD0U2uQcIQtzB4ksvOXqog';
const Code_Push_ios_Key = 'HQbsaZXZkcTkTAuJBQjoJ0uGwmov4ksvOXqog';

class MineScreen extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      remarks: '',
      isShowUpVersion: false,
      isShowProgress: false,
      version: '',
      progress: '',
    };
  }

  componentDidMount() {
    // 七牛的原生通知统一管理
    QNEngine.eventEmitter({
      onProgress: (data) => {
        console.log(data.percent);
      },
      onComplete: (data) => {
        let hash = null;
        if (Platform.OS == 'ios') {
            hash = data.msg
        } else {
            hash = data.key
        }
        console.log(hash);
        this.goCommint(hash);
      },
      onError: (data) => {
        Loading.hide();
        console.log(data);
        switch (data.code) {
        case '-2':
          Toast.show('任务已暂停');
          break;
        default:
          Toast.show(`错误：${data.msg}`);
          break;
        }
      },
    });
  }

    //图片上传完成 开始更新用户头像
  goCommint = (hash) => {
    //上传图片
    requestApi
        .updateUserInfo({urlAddr: hash })
        .then(data => {
            Loading.hide();
            Toast.show("修改成功", 500);
            this.props.getUserInfo();// 更新redux 数据
        })
        .catch(err => {
            Loading.hide();
            Toast.show(err.msg, 500);
        });
  };

  componentWillUnmount() {
    QNEngine.removeEmitter();
  }

  render() {
    const userInfo = this.props.userInfo ? this.props.userInfo : this.props.token;
    return (
      <View style={{ flex: 1, backgroundColor: '#F9F9F9' }}>
        <NavigationBar
          navigation={this.props.navigation}
          isBack={true}
          title={'我的'}
        />
        <ScrollView
          showsVerticalScrollIndicator={false}
          style={{
            width: '100%',
            backgroundColor: '#F9F9F9',
          }}
        >
          <View
            style={{
              width: '100%',
              paddingTop: 30,
              paddingBottom: 30,
              backgroundColor: '#fff',
              alignItems: 'center',
            }}
          >
            <TouchableOpacity
              onPress={
                this.photograph.bind(this)
              }>
              <Image
                resizeMode={'cover'}
                source={userInfo.urlAddr ? { uri: "http://cdn.traceche.com/" + userInfo.urlAddr} : image.avatar_default}
                style={{ borderRadius: 40, width: 80, height: 80 }}/>
            </TouchableOpacity>

            <TouchableOpacity
              onPress={
                this.photograph.bind(this)
              }>
              <Text style={{
                marginTop: 20,
                color: '#606060',
                fontSize: 14,
              }}>点击更换头像</Text>
            </TouchableOpacity>
          </View>

          <View style={{ height: 10, backgroundColor: '#F9F9F9' }} />

          <TouchableOpacity
            style={styles.itemStyle}
            onPress={() => {
              NavigationService.navigate('EnterpriseInfoScreen');
            }}
          >
            <Image source={image.ic_enterprise} style={styles.ImageStyle} />

            <Text
              style={{
                marginLeft: 15,
                color: '#606060',
                fontSize: 18,
              }}
            >
              企业信息
            </Text>
            <View style={{ flex: 1 }} />
            <Image
              style={{ width: 20, height: 20 }}
              source={image.ic_right_arrow}
            />
          </TouchableOpacity>
          <View style={styles.divider} />
          <TouchableOpacity
            style={styles.itemStyle}
            onPress={() => {
              NavigationService.navigate('InvoiceInfoScreen');
            }}
          >
            <Image source={image.ic_invoice} style={styles.ImageStyle} />

            <Text
              style={{
                marginLeft: 15,
                color: '#606060',
                fontSize: 18,
              }}
            >
              开票信息
            </Text>
            <View style={{ flex: 1 }} />
            <Image
              style={{ width: 20, height: 20 }}
              source={image.ic_right_arrow}
            />
          </TouchableOpacity>
          <View style={styles.divider} />
          <TouchableOpacity
            style={styles.itemStyle}
            onPress={() => {
              NavigationService.navigate('AccountSafeScreen');
            }}
          >
            <Image source={image.ic_safety} style={styles.ImageStyle} />

            <Text
              style={{
                marginLeft: 15,
                color: '#606060',
                fontSize: 18,
              }}
            >
              账号安全
            </Text>
            <View style={{ flex: 1 }} />
            <Image
              style={{ width: 20, height: 20 }}
              source={image.ic_right_arrow}
            />
          </TouchableOpacity>
          <View style={styles.divider} />

          {!userInfo.uperUserId && (
            <TouchableOpacity
              style={styles.itemStyle}
              onPress={() => {
                NavigationService.navigate('SubAccountScreen');
              }}
            >
              <Image source={image.ic_sub_account} style={styles.ImageStyle} />

              <Text
                style={{
                  marginLeft: 15,
                  color: '#606060',
                  fontSize: 18,
                }}
              >
                子账号
              </Text>
              <View style={{ flex: 1 }} />
              <Image
                style={{ width: 20, height: 20 }}
                source={image.ic_right_arrow}
              />
            </TouchableOpacity>
          )}

          <View style={{ height: 10, backgroundColor: '#F9F9F9' }} />

          <TouchableOpacity
            style={styles.itemStyle}
            onPress={() => {
              NavigationService.navigate('ServiceAgreementScreen');
            }}
          >
            <Image
              source={image.ic_service_agreement}
              style={styles.ImageStyle}
            />

            <Text
              style={{
                marginLeft: 15,
                color: '#606060',
                fontSize: 18,
              }}
            >
              服务协议
            </Text>
            <View style={{ flex: 1 }} />
            <Image
              style={{ width: 20, height: 20 }}
              source={image.ic_right_arrow}
            />
          </TouchableOpacity>
          <View style={styles.divider} />
          <TouchableOpacity
            style={styles.itemStyle}
            onPress={this.checkForUpdate.bind(this)}
          >
            <Image source={image.ic_update} style={styles.ImageStyle} />

            <Text
              style={{
                marginLeft: 15,
                color: '#606060',
                fontSize: 18,
              }}
            >
              检查更新
            </Text>
            <View style={{ flex: 1 }} />
            <View style={{ paddingRight: 5 }}>
              <Text>{global.appVersion ? global.appVersion : '获取版本号失败'}</Text>
            </View>
            <Image
              style={{ width: 20, height: 20 }}
              source={image.ic_right_arrow}
            />
          </TouchableOpacity>
          <View style={{ height: 10, backgroundColor: '#F9F9F9' }} />
          <TouchableOpacity
            style={[
              styles.itemStyle,
              { marginBottom: 50, justifyContent: 'center' },
            ]}
            onPress={this.logoutApp.bind(this)}
          >
            <Text
              style={{
                color: '#D0021B',
                fontSize: 18,
                fontWeight: 'bold',
              }}
            >
              退出账号
            </Text>
          </TouchableOpacity>
        </ScrollView>

        {this.showUpVersionView()}
        {this.showProgressView()}

        <View style={{ height: safeAreaBottomHeight }} />
      </View>
    );
  }

  showProgressView() {
    return (
      <AlertView
        isShow={this.state.isShowProgress}
        position={{ justifyContent: 'center' }}
        contentStyle={{ alignItems: 'center' }}
      >
        <View style={{ width: screenWidth - 58, alignItems: 'center' }}>
          <Text style={{ color: '#202020', fontSize: 15 }}>
            正在加载 {parseInt(this.state.progress * 100, 10)}%
          </Text>
          <View
            style={{
              marginTop: 18,
              height: 16,
              backgroundColor: '#E5E5E5',
              flexDirection: 'row',
              width: screenWidth - 58,
            }}
          >
            <View
              style={{
                backgroundColor: '#00A0E9',
                height: 16,
                width: `${this.state.progress * 100}%`,
              }}
            />
          </View>
        </View>
        <View />
      </AlertView>
    );
  }

  showUpVersionView() {
    return (
      <AlertView
        isShow={this.state.isShowUpVersion}
        position={{ justifyContent: 'center' }}
        contentStyle={{ alignItems: 'center' }}
      >
        <View
          style={{
            borderRadius: 8,
            width: screenWidth - 58,
            backgroundColor: '#fff',
            alignItems: 'center',
          }}
        >
          <Image source={image.account_error} style={{ marginTop: -43 }} />
          <Text style={{ color: '#5292FF', fontSize: 19, marginTop: 24 }}>
            新版本升级
          </Text>
          <View style={{ width: screenWidth - 58, marginTop: 30 }}>
            <Text
              style={{
                color: '#202020',
                fontSize: 14,
                fontWeight: 'bold',
                marginLeft: 20,
                marginRight: 20,
              }}
            >
              辛巴支付{this.state.version}更新了
            </Text>
            <Text
              style={{
                color: '#808080',
                fontSize: 12,
                marginLeft: 20,
                marginRight: 20,
                marginTop: 13,
              }}
            >
              1.修复了已知bug
            </Text>
            <Text
              style={{
                color: '#808080',
                fontSize: 12,
                marginLeft: 20,
                marginRight: 20,
                marginTop: 6,
              }}
            >
              2.优化界面
            </Text>
          </View>
          <View style={{ marginTop: 40 }}>
            <TouchableOpacity
              style={{
                width: 150,
                marginLeft: 12,
                marginRight: 20,
                marginBottom: 20,
                backgroundColor: '#4A90E2',
                justifyContent: 'center',
                alignItems: 'center',
                height: 36,
                borderRadius: 18,
              }}
              onPress={this.upVersionAction.bind(this)}
            >
              <Text style={{ color: '#202020', fontSize: 14 }}>更新</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={{
                width: 150,
                marginLeft: 12,
                marginRight: 20,
                marginBottom: 35,
                backgroundColor: '#ccc',
                justifyContent: 'center',
                alignItems: 'center',
                height: 36,
                borderRadius: 18,
              }}
              onPress={this.cancelUpdate.bind(this)}
            >
              <Text style={{ color: '#202020', fontSize: 14 }}>取消</Text>
            </TouchableOpacity>
          </View>
        </View>
        <View />
      </AlertView>
    );
  }

  cancelUpdate() {
    this.setState({ isShowUpVersion: false });
  }

  // 拍照
  photograph() {
    const options = {
      title: null, // 选择器的标题，可以设置为空来不显示标题
      cancelButtonTitle: '取消',
      takePhotoButtonTitle: '照相机', // 调取摄像头的按钮，可以设置为空使用户不可选择拍照
      chooseFromLibraryButtonTitle: '相册', // 调取相册的按钮，可以设置为空使用户不可选择相册照片
      mediaType: 'photo', // 'photo' or 'video'
      maxWidth: 100, // photos only默认为手机屏幕的宽，高与宽一样，为正方形照片
      maxHeight: 100, // photos only
      allowsEditing: true, // 当用户选择过照片之后是否允许再次编辑图片
    };

    ImagePicker.showImagePicker(options, (response) => {
      if (response.didCancel) {
        Toast.show('取消修改头像', 2000);
      } else if (response.error) {
        // ('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        // ('User tapped custom button: ', response.customButton);
      } else {
        Loading.show();
        requestApi
          .getQiniuToken()
          .then((res) => {
            const params = {
              id: '555',
              filePath: response.uri,
              upKey: null,
              upToken: res,
              zone: 3,
            };
            QNEngine.setParams(params);

            // 开始上传任务
            QNEngine.startTask();
          })
          .catch((err) => {
            Toast.show(err.msg, 1000);
          });
      }
    });
  }

  // 退出登录
  logoutApp() {
    // 清空token
    global.storage
      .save({
        key: LoginToken,
        data: '',
        expires: null,
      })
      .then((ret) => {
        global.token = ''; // 清空全局存储token
        Toast.show('退出成功');
        this.props.getUserInfo({clear: true}); //清楚数据
        NavigationService.reset('Drawer');
      })
      .catch((err) => {
        Toast.show('退出失败');
      });

  }

  // 开始更新
  checkForUpdate() {
    const Key = Platform.OS === 'ios' ? Code_Push_ios_Key : Code_Push_Key;
    CodePush.checkForUpdate(Key)
      .then((update) => {
        if (update) {
          this.setState({
            isShowUpVersion: true,
            version: `${update.appVersion} ${ update.label}`,
          });
        } else {
          // 不需要更新 3秒后跳转登录页面
          Toast.show('已是最新版本');
        }
      })
      .catch((e) => {
        // 不需要更新 3秒后跳转登录页面
        Toast.show('检测出错');
      });
  }

  // 关闭弹框开始更新
  upVersionAction() {
    this.syncImmediate();
    this.setState({ isShowUpVersion: false });
  }

  // 如果有更新的提示
  syncImmediate() {
    CodePush.sync(
      {
        installMode: CodePush.InstallMode.IMMEDIATE,
        updateDialog: null,
      },
      this.codePushStatusDidChange.bind(this),
      this.codePushDownloadDidProgress.bind(this),
    );
  }

  codePushStatusDidChange(syncStatus) {
    switch (syncStatus) {
    case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
      // ("检查更新");
      break;
    case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
      // ("下载安装包");
      break;
    case CodePush.SyncStatus.AWAITING_USER_ACTION:
      // ("等待用户协作");
      break;
    case CodePush.SyncStatus.INSTALLING_UPDATE:
      // ("安装中");
      break;
    case CodePush.SyncStatus.UP_TO_DATE:
      // ("已经是最新版本了");
      break;
    case CodePush.SyncStatus.UPDATE_IGNORED:
      // ("取消更新");
      break;
    case CodePush.SyncStatus.UPDATE_INSTALLED:
      // ("更新完成");
      break;
    case CodePush.SyncStatus.UNKNOWN_ERROR:
      // ("未知错误");
      break;
    }
    Toast.show('检查完成');
  }

  codePushDownloadDidProgress(progress) {
    if (!progress.receivedBytes) {
      Toast.show('更新出错了，请稍后重试', 1000);
      this.setState({ isShowProgress: false });
      return;
    }
    if (!progress.totalBytes) {
      Toast.show('更新出错了，请稍后重试', 1000);
      this.setState({ isShowProgress: false });
      return;
    }
    if (progress) {
      this.setState({ isShowProgress: true });
      const currProgress = parseFloat(
        progress.receivedBytes / progress.totalBytes,
      ).toFixed(2);
      if (currProgress >= 1) {
        this.setState({ isShowProgress: false });
      } else {
        this.setState({ progress: currProgress });
      }
    }
  }
}

const styles = StyleSheet.create({
  itemStyle: {
    paddingLeft: 15,
    paddingRight: 15,
    height: 60,
    flexDirection: 'row',
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  ImageStyle: {
    width: 30,
    height: 30,
  },
  divider: {
    marginLeft: 70,
    height: 1,
    backgroundColor: '#F9F9F9',
    transform: [{ scaleY: 0.5 }],
  },
});

export default connect(
  ({ userInfo, token }) => ({
    userInfo,
    token,
  }),
  {
    getUserInfo: actions.getUserInfo,
  },
)(MineScreen);
